package com.heima.comment.service.impl;

import com.heima.comment.dto.*;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentRepayService;
import com.heima.comment.vo.ApCommentRepayVo;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentRepayServiceImpl implements ICommentRepayService {


    @Autowired
    private UserFeign userFeign;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult saveRepay(CommentRepaySaveDto dto) {
        // 判断内容是否大于140字
        if (dto == null || dto.getContent().length() > 140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 判断用户是否登录(要求使用手机号和密码登录的用户)
        User user = UserThreadLocalUtil.get();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 安全过滤 -- 阿里云文本审核  todo自行实现
        ApCommentRepay comment = new ApCommentRepay();
        comment.setUserId(user.getUserId());
        // 根据用户id查询用户,调用用户微服务提供的远程接口
        ResponseResult<ApUser> userResponseResult = userFeign.getById(user.getUserId());
        if (userResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApUser apUser = userResponseResult.getData();
            comment.setUserName(apUser.getName());
        }
        comment.setCommentId(dto.getCommentId());
        comment.setContent(dto.getContent());
        comment.setLikes(0);
        comment.setCreatedTime(new Date());
        // 保存评论
        mongoTemplate.save(comment);
        // 将评论表的回复数量+1
        Query commentQuery = new Query();
        commentQuery.addCriteria(Criteria.where("_id").is(dto.getCommentId()));
        // 更新条件
        Update update = new Update();
        update.inc("repay");
        mongoTemplate.updateFirst(commentQuery,update, ApComment.class);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult load(CommentRepayDto dto) {
        // 根据文章id查询评论列表
        // 按照评论时间排列
        // 分页判断数据小于前端传递的最小时间
        // 每页默认显示10条评论数据
        if (dto.getSize() == null || dto.getSize() <= 0 || dto.getSize() >= 50){
            dto.setSize(10);
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        // 分页和排序
        query.limit(dto.getSize());
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApCommentRepay> apCommentRepayList = mongoTemplate.find(query, ApCommentRepay.class);
        // 判断当前用户是否登录
        User user = UserThreadLocalUtil.get();
        // TODO  登录用户需要查看当前返回的列表中是否已经有点赞记录
        if (user != null && user.getUserId() != 0){
            List<ApCommentRepayVo> commentRepayVoList = new ArrayList<>();
            for (ApCommentRepay commentRepay : apCommentRepayList) {
                ApCommentRepayVo commentRepayVo = new ApCommentRepayVo();
                BeanUtils.copyProperties(commentRepay,commentRepayVo);
                Boolean hasKey = redisTemplate.hasKey("comment_repay_like_" + user.getUserId() + "_" + commentRepay.getId());
                commentRepayVo.setOperation(hasKey?0:1); //0代表当前登录人对这个回复点赞
                commentRepayVoList.add(commentRepayVo);
            }
            return ResponseResult.okResult(commentRepayVoList);
        }
        return ResponseResult.okResult(apCommentRepayList);
    }

    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {
        // 获取当前的用户
        User user = UserThreadLocalUtil.get();
        if (user == null || user.getUserId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
            // 构建点赞记录
            ApCommentRepayLike like = new ApCommentRepayLike();
            like.setUserId(user.getUserId());
            like.setCommentRepayId(dto.getCommentRepayId());
            like.setOperation(dto.getOperation());
            // 保存点赞或取消点赞记录
            mongoTemplate.save(like);

            // 更新回复的点赞数量+1或者-1
            Query commentQuery = new Query();
            commentQuery.addCriteria(Criteria.where("_id").is(dto.getCommentRepayId()));
            Update update = new Update();
            if (dto.getOperation() == 1) {
                // 取消点赞
                update.inc("likes", -1);
                // 删除在Redis中做的标记
                redisTemplate.delete("comment_repay_like_" + user.getUserId() + "_" + dto.getCommentRepayId());
            } else {
                // 点赞
                update.inc("likes", 1);
                // 删除在Redis中做的标记
                redisTemplate.boundValueOps("comment_repay_like_" + user.getUserId() + "_" + dto.getCommentRepayId()).set("");//这里放什么值无所谓  只要判断存在这个key就可以了
            }
        mongoTemplate.updateFirst(commentQuery, update, ApCommentRepay.class);
        return ResponseResult.okResult();
    }
}
